package com.youme.section.shop

import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import com.hjq.toast.ToastUtils
import com.hyphenate.easeim.R
import com.youme.api.Callback
import com.youme.model.Rest
import com.youme.model.param.SearchCateen
import com.youme.section.shop.adapter.HotDianAdapter
import com.youme.viewmodel.YouMeApiViewModel
import kotlinx.android.synthetic.main.demo_activity_search_rest.*
import kotlinx.coroutines.launch

class SearchActivity : AppCompatActivity() {
    val favoriteBeanList = arrayListOf<Rest>()
    val adapter: HotDianAdapter = HotDianAdapter(favoriteBeanList, this)

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.demo_activity_search_rest)
        initViewAndData()
    }

    fun initViewAndData() {
        initRecycle()
        commonTitleBar.setOnClickListener {
            finish()
        }
        tv_search.setOnClickListener {
            if (query.text.isNullOrBlank()) {
                ToastUtils.show("请输入搜索内容")
            } else {
                var mViewModel = ViewModelProvider(this).get(YouMeApiViewModel::class.java)
                lifecycleScope.launch {
                    mViewModel.listSearch(SearchCateen(1.1, 1.2, query.text.toString()), object : Callback<List<Rest>> {
                        override fun onSuccess(value: List<Rest>) {
                            favoriteBeanList.clear()
                            favoriteBeanList.addAll(value)
                            hot_dian_recycleview.adapter?.notifyDataSetChanged()
                        }

                        override fun onFailed(errorCode: Int, errorMessage: String, throwable: Throwable?) {
                            ToastUtils.show("请求失败,$errorCode,$errorMessage,$throwable")
                        }
                    })
                }
            }
        }
    }

    private fun initRecycle() {
        val layoutManager = LinearLayoutManager(this)
        hot_dian_recycleview.layoutManager = layoutManager
        hot_dian_recycleview.adapter = adapter
    }
}